package day11;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//测试公平锁
public class TestFair{
    //默认是非公平锁
    ReentrantLock lock=new ReentrantLock(true);
    public void test(){
        String name=Thread.currentThread().getName();
        try {
            lock.lock();
            System.out.println(name+"获取了锁,开始执行....");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(name+"执行结束了,释放了锁");
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        TestFair fair=new TestFair();
        for(int i=0;i<5;i++){
            new Thread(()->{
                while(true){
                    fair.test();
                }
            },"线程:"+i).start();
        }
    }
}
